<?php

namespace App\Http\Controllers\WF\Systems;

use DB;
use Config;
use Hash;
use Log;
use Carbon\Carbon;
use Ramsey\Uuid\Uuid;
use App\Http\Controllers\WF\ApiController;
use Illuminate\Http\Request;
use Jishulin\WorkFlowEngine\Tools\Tools;
use Jishulin\WorkFlowEngine\Tools\Birts;
use Jishulin\WorkFlowEngine\Tools\Jobs;
use Jishulin\WorkFlowEngine\Tools\Processes;
use Jishulin\WorkFlowEngine\Tools\Utils\ProcessUtil;

class JobController extends ApiController
{
    // 获取列表界面配置信息
    public function getWorkFlowTodoConfig(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');

        $res = Tools::getInstance()->getWorkFlowTodoConfig($flowId, $nodeId);

        if ($res['error']) {
            return $this->jsonReturns(50000, $res['message']);
        }

        return $this->jsonReturns(10000, $this->success, $res['data']);
    }

    public function getJobTodoList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');
        $keyword = $request->input('keyword');
        $search = $request->input('search', []);
        // 业务自定义校验（自行扩展开发）

        try {
            $res = Processes::getInstance()->getJobTodoList(
                $offest,
                $limit,
                $flowId,
                $nodeId,
                $keyword,
                $search,
                $this->apiUser
            );

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            // 日志记录(自行处理)
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function jobCommitOrSaveOfWorkFlow(Request $request)
    {
        $param = $request->all();
        // 业务自定义校验（自行扩展开发）

        DB::beginTransaction();
        try {
            // 处理业务数据
            $table = ProcessUtil::getMainJobTableByFlowId($param['flowId']);
            if (isset($param['main']['id'])) unset($param['main']['id']);
            $main = $param['main'];
            unset($param['main']);
            $param['main'][$table] = $main;

            $res = Processes::getInstance()->jobProcessDealWork($param, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            DB::commit();
            // 第三方推送等信息自定义处理（不放在事物当中）

            return $this->jsonReturns(10000, $this->success, $res['data'] ?? []);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function jobExamOrSubmitWorkFlow(Request $request)
    {
        $param = $request->all();
        // 业务自定义校验（自行扩展开发）

        DB::beginTransaction();
        try {
            $res = Processes::getInstance()->jobProcessDealExam($param, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            DB::commit();
            // 第三方推送等信息自定义处理（不放在事物当中）

            return $this->jsonReturns(10000, $this->success, $res['data'] ?? []);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function jobProcessSubmit(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');
        $jobId = $request->input('jobId');
        $processId = $request->input('processId');

        DB::beginTransaction();
        try {
            $map = [
                'processId' => $processId,
                'jobId' => $jobId,
                'flowId' => $flowId,
                'nodeId' => $nodeId
            ];
            $res = Processes::getInstance()->jobProcessSubmit($map, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            DB::commit();
            // 第三方推送等信息自定义处理（不放在事物当中）

            return $this->jsonReturns(10000, $this->success, $res['data'] ?? []);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function printJobDetailByUuid(Request $request)
    {
        $flowId = $request->input('flowId');
        $uuId = $request->input('uuId');
        $jobId = $request->input('jobId');

        // 整理业务数据
        $mapData = [];
        $birtJobData = Processes::getInstance()->getBirtJobData($flowId, $jobId, $uuId);
        // 获取主表业务数据
        $mapData['single'] = $birtJobData['single'];
        $mapData['table'] = $birtJobData['table'] ?? [];

        $fileName = $birtJobData['single']['NUMBER'] . '-' . $birtJobData['single']['NAME'] . '-' . Birts::getInstance()->getBirtNameByUuid($uuId);
        $mapData['fileName'] = $fileName;

        try {
            $res = Birts::getInstance()->birtPrintByUuid($uuId, $mapData, 1);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function exportJobListByNodeId(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');

        try {
            $res = Birts::getInstance()->birtExportJobList($flowId, $nodeId, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getJobExamDetail(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');
        $jobId = $request->input('jobId');

        try {
            $res = Processes::getInstance()->getJobProcessExamDetail($flowId, $nodeId, $jobId);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getJobDataDetail(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');
        $jobId = $request->input('jobId');

        try {
            $res = Processes::getInstance()->getJobDataDetail($flowId, $nodeId, $jobId);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getJobFormDefaultConfig(Request $request)
    {
        $flowId = $request->input('flowId');
        $nodeId = $request->input('nodeId');

        try {
            $res = Processes::getInstance()->getJobFormDefaultConfig($flowId, $nodeId);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getJobFormConfigByFormId(Request $request)
    {
        $formId = $request->input('formId');

        try {
            $res = Tools::getInstance()->getFormDesignConfigByFormId($formId);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    // 业务分析统计数据
    public function getWorkFlowAnalysis(Request $request)
    {
        $flowId = $request->input('flowId');

        try {
            $res = Processes::getInstance()->getWorkFlowAnalysis($flowId, $this->apiUser, [
                'table' => 'wf_users', 'primary' => 'id', 'column' => ['realname', 'avatar']
            ], \App\Http\Controllers\Wf\Common\Share::class);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            if ($this->apiUser['user_type'] == 2) {
                $res2 = Processes::getInstance()->getWorkFlowForUser($this->apiUser, [
                    'table' => 'wf_users', 'primary' => 'id', 'column' => ['realname', 'avatar']
                ]);

                if ($res2['error']) {
                    return $this->jsonReturns(50000, $res2['message']);
                }

                $res['data']['jobBusInfo'] = $res2['data'];
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getWorkFlowByBelongForEnabled()
    {
        try {
            $res = Tools::getInstance()->getWorkFlowByBelong($this->apiUser['company_id'], 1);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            $jsonData = [];
            foreach ($res['data'] as $k => $v) {
                $v = (array)$v;
                $jsonData[] = [
                    'flowId' => $v['wf01001'],
                    'flowName' => $v['wf01002'],
                ];
            }

            return $this->jsonReturns(10000, $this->success, $jsonData);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getJobWorkFlowNodeAnalysis(Request $request)
    {
        $flowId = $request->input('flowId');
        try {
            $res = Processes::getInstance()->getJobWorkFlowNodeAnalysis($flowId, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getHistoryJobList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $flowId = $request->input('flowId');
        $keyword = $request->input('keyword');

        $NODEID = $request->input('NODEID', '');
        $outWhere = [];
        if ($NODEID) {
            $outWhere[] = ['NODEID', '=', $NODEID];
        }

        try {
            $res = Processes::getInstance()->getHistoryJobList(
                $offest,
                $limit,
                $flowId,
                $keyword,
                $outWhere,
                $this->apiUser
            );

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getHistoryJobDataDetail(Request $request)
    {
        $primaryId = $request->input('id');

        try {
            $res = Processes::getInstance()->getHistoryJobDataDetail($primaryId);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getWorkNodeByFlowIdForDict(Request $request)
    {
        $flowId = $request->input('flowId');

        $nodeDictData = Tools::getInstance()->getWorkNodeByFlowIdForDict($flowId);

        return $this->jsonReturns(10000, $this->success, $nodeDictData);
    }

    public function getCustomerColumnsConfig(Request $request)
    {
        $flowId = $request->input('flowId');

        $res = Tools::getInstance()->getCustomerColumnsConfig($flowId, $this->apiUser);

        if ($res['error']) {
            return $this->jsonReturns(50000, $res['message']);
        }

        return $this->jsonReturns(10000, $this->success, $res['data']);
    }

    public function getCustomerJobList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $flowId = $request->input('flowId');
        $keyword = $request->input('keyword');
        // 业务自定义校验（自行扩展开发）

        try {
            $outWhere = [];
            // 默认当前业务员只能查看自己的订单
            if ($this->apiUser['user_type'] == 2) {
                $outWhere[] = ['wf12010', '=', $this->apiUser['id'], 'AND'];
            }
            $res = Processes::getInstance()->getCustomerJobList(
                $offest,
                $limit,
                $flowId,
                $keyword,
                $outWhere,
                $this->apiUser
            );

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }

            return $this->jsonReturns(10000, $this->success, $res['data']);
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function exportCustomerListByFlowId(Request $request)
    {
        $flowId = $request->input('flowId');

        try {
            $outWhere = [];
            // 默认当前业务员只能查看自己的订单
            if ($this->apiUser['user_type'] == 2) {
                $outWhere[] = ['wf12010', '=', $this->apiUser['id'], 'AND'];
            }
            $res = Birts::getInstance()->exportCustomerListByFlowId($flowId, $outWhere, $this->apiUser);

            if ($res['error']) {
                return $this->jsonReturns(50000, $res['message']);
            }
        } catch (\Exception $e) {
            Log::error((string)$e);
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function getCustomerColumnsSet(Request $request)
    {
        $flowId = $request->input('flowId');

        $jobs = Jobs::getInstance();

        $res = $jobs->getCustomerColumnsSet($flowId, $this->apiUser);
        if ($res['error']) {
            return $this->jsonReturns(50000, $res['message']);
        }

        return $this->jsonReturns(10000, $this->success, $res['data']);
    }

    public function customerColumnsSetSave(Request $request)
    {
        $flowId = $request->input('flowId');
        $type = $request->input('type');
        $target = $request->input('target');

        $jobs = Jobs::getInstance();

        $res = $jobs->customerColumnsSetSave($type, $flowId, $target, $this->apiUser['id']);

        if ($res['error']) {
            return $this->jsonReturns(50000, $res['message']);
        }

        return $this->jsonReturns(10000, $this->success);
    }
}
